import inspect
import os
import sys
import unittest
from types import ClassType
from selenium import webdriver
import selenium.webdriver.support.ui as ui


DRIVERS = [
    webdriver.Firefox,
#    webdriver.Chrome
    ]

def get_driver():
    for driver in DRIVERS:
        yield driver

def runner(base_class):
    print 'Running %s ...' % base_class

    suites = []
    results = unittest.TestResult()

    for driver in get_driver():

        def setUp(self):
            self.verificationErrors = []
            self.driver.maximize_window()
            self.base_url = 'http://localhost/'
            self.driver.implicitly_wait(15)
            self.waiter = ui.WebDriverWait(self.driver, 3)

        def tearDown(self):
            self.driver.quit()
            self.assertEqual([], self.verificationErrors)

        utest = ClassType('AutoUnitTest_%s' % driver, (unittest.TestCase, base_class), { 'driver': driver() })
        utest.setUp = setUp
        utest.tearDown = tearDown

        suites.append(unittest.TestLoader().loadTestsFromTestCase(utest))

    unittest.TestSuite(suites)(results)

    for obj, error in results.errors:
        print 'ERROR IN: ', obj
        print error

    for obj, error in results.failures:
        print 'FAILURES IN: ', obj
        print error

if __name__ == "__main__":
    test_classes = []

    for topdir, dirs, filenames in os.walk('cases'):
        for filename in filenames:
            if filename.endswith('Test.py'):
                test_name = filename.replace('.py', '')
                import_path = 'cases.%s' % test_name
                __import__(import_path)
                clsmembers = inspect.getmembers(sys.modules[import_path], inspect.isclass)
                for class_name, class_def in clsmembers:
                    if class_name == test_name:
                        test_classes.append(class_def)

    print 'Available tests: %s' % test_classes
    for test_class in test_classes:
        runner(test_class)
